import 'dart:convert';

import 'package:eplorex/models/server_message.dart';

import '../pages/message/convlist_page.dart';
import '../utils/HttpUtil.dart';

class ConversationDao {
  static Future<List<ServerMessage>> queryConvMessage(num cid) async {
    var response = await HttpUtil.getInstance()
        .get("/api/chat/v1/conv/message", data: {'cid': cid});
    if (response?.statusCode == 200 && response?.data != null) {
      return response?.data['data']
          .map<ServerMessage>((e) => ServerMessage.fromJson(e))
          .toList();
    }
    return [];
  }

  static Future<List<ConversationItem>?> getConversations() async {
    final response = await HttpUtil.getInstance().get("/api/chat/v1/convlist",
        data: {'time': DateTime.now().millisecondsSinceEpoch});
    if (response?.statusCode == 200) {
      List<ConversationItem> posts = response!.data['data']
              ?.map<ConversationItem>((item) => ConversationItem.fromJson(item))
              .toList() ??
          [];
      return posts;
    }
    return List.empty();
  }

  static Future<ConversationItem?> getUserPairConversation(
      num fromUserId, num toUserId) async {
    var response = await HttpUtil.getInstance().get(
        "/api/chat/v1/conv/user/message",
        data: {'fromUserId': fromUserId, 'toUserId': toUserId});
    if (response?.statusCode == 200 && response?.data != null) {
      return ConversationItem.fromJson(response?.data['data']);
    }
    return null;
  }

  static Future<void> deleteConv(num cid) async {
    var response = await HttpUtil.getInstance()
        .post('/api/chat/v1/conv/delete', data: cid);
    if (response?.statusCode == 200 && response?.data == true) {
      print("成功");
    }
    print("失败");
  }

  static Future<int> topRankConv(num cid, bool isTop) async {
    var response = await HttpUtil.getInstance().post('/api/chat/v1/conv/top',
        data: jsonEncode({'cid': cid, 'top': isTop}));
    if (response?.statusCode == 200 && response?.data != null) {
      return response?.data['data'];
    }
    return 0;
  }
}
